package com.xtoad.ecms.common.web.interceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import javax.annotation.Resource;

/**
 * 拦截器注册类
 *
 * @author xtoad
 * @date 2020/05/29
 */
@Configuration
public class ConfigInterceptor extends WebMvcConfigurationSupport {

    @Resource
    AuthenticationInterceptor authenticationInterceptor;

    /**
     * 统一认证Token 拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authenticationInterceptor).addPathPatterns("/**");
        super.addInterceptors(registry);
    }

    /**
     * 支持跨域
     *
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 允许跨域访问的链接 "/**" 表示允许所有链接
        registry.addMapping("/**")
                // 允许的http方法(GET,PUT,POST,DELETE...),"*"表示允许所有方法
                .allowedMethods("*");
    }

    /**
     * 设置默认 ContentType
     *
     * @param configurer 配置对象
     */
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.ignoreAcceptHeader(true)
                .defaultContentType(MediaType.APPLICATION_JSON_UTF8);
    }
}
